package com.example.webcrawler;

import com.example.webcrawler.controller.FlowTestController;
import com.example.webcrawler.service.mpl.HttpsProxyService;
import com.example.webcrawler.service.mpl.WebAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.boot.CommandLineRunner;

@SpringBootApplication
@EnableWebSocket
public class WebCrawlerApplication implements CommandLineRunner {

    @Autowired
    private HttpsProxyService httpsProxyService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(WebCrawlerApplication.class, args);

        // 建立服务之间的依赖关系
        WebAnalysisService webAnalysisService = context.getBean(WebAnalysisService.class);
        FlowTestController flowTestController = context.getBean(FlowTestController.class);
        HttpsProxyService httpsProxyService = context.getBean(HttpsProxyService.class);

        // 设置WebSocket请求广播器
        webAnalysisService.setRequestBroadcaster(flowTestController::broadcastRequest);

        // 设置拦截检查器
        webAnalysisService.setInterceptChecker(flowTestController::shouldIntercept);

        // 检查Playwright配置
        System.out.println("=====================================");
        System.out.println("检查Playwright配置:");
        System.out.println(webAnalysisService.getPlaywrightInfo());

        boolean isReady = checkPlaywrightInstallation(webAnalysisService);
        if (!isReady) {
            System.err.println("警告: Playwright未正确配置，动态分析功能可能无法正常工作");
            System.err.println("请确保浏览器已安装或设置正确的PLAYWRIGHT_BROWSERS_PATH环境变量");
        } else {
            System.out.println("Playwright已准备就绪");
        }
        System.out.println("=====================================");
    }

    private static boolean checkPlaywrightInstallation(WebAnalysisService service) {
        try {
            // 尝试创建Playwright实例来验证安装
            try (com.microsoft.playwright.Playwright playwright = com.microsoft.playwright.Playwright.create()) {
                // 尝试启动浏览器来验证安装
                com.microsoft.playwright.Browser browser = playwright.chromium()
                        .launch(new com.microsoft.playwright.BrowserType.LaunchOptions().setHeadless(true));
                browser.close();
                return true;
            }
        } catch (Exception e) {
            System.err.println("Playwright安装检查失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 启动HTTPS代理服务器
     */
    @Override
    public void run(String... args) throws Exception {
        // 确保HTTPS代理服务器在端口8081上运行
        httpsProxyService.startProxy(8081);
    }

    /**
     * WebSocket支持配置
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
